package util.webSearch;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;

import util.io.FileInput;
import util.io.URLInput;
import util.parser.ParseBingWebResults;

public class BingQueryJsonHttp  implements Constants {

	/**
	 * @param args
	 */

	private String chooseID(){

		int MAX = Constants.BING_ID.length - 1;
		int index = (int) Math.round(((double) Math.random() * (MAX)));
		
		return Constants.BING_ID[index];
		
	}
	
	public  LinkedList<WebResult> bingQuery(String query, int max_results, String path) throws IOException {

		LinkedList<WebResult> res = new LinkedList<WebResult>();
		
			String post = null;
		
			
			
			String id= chooseID();
			
			String url = "http://api.bing.net/json.aspx?AppId="+id+"&Version=2.2&Market=en-US&Query="
			+URLEncoder.encode(query, "utf8")+
			"&Sources=web+spell&Web.Count="+max_results+"&JsonType=raw";
			

			post = URLInput.readFromURL(url);
			
						
			if(post == null  || (post.equals("")) ){
				
				
				return null;
			}
			
			res = ParseBingWebResults.results(query, post);
			
		
	
		return res;

	}
	
	
	public static void main(String[] args) throws IOException  {
	 String path =	"/dictionary/user_agent_list.txt";
		if (args.length != 1) {

			System.out.println("Input file not specified");
			System.exit(1);
		}

		FileInput in = new FileInput(args[0]);

		BingQueryJsonHttp q = new BingQueryJsonHttp();
		
		String line = in.readString();
		
		while (line != null) {

			LinkedList<WebResult> list = q.bingQuery(line, 10,path);

			for (int i = 0; i < list.size(); i++) {
				WebResult result = list.get(i);
				System.out.println(line.trim()+ "\t"+ result.getUrl()+ "\t"+ result.getTitle()+ "\t"+ result.getSnippet().trim().replaceAll("\\s+"," ")+ "\t" + (i+1));;

			}

			line = in.readString();
		}

	}

}
